package com.cloudcc.mobile.view.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.cloudcc.cloudframe.util.DensityUtils;
import com.cloudcc.cloudframe.util.SharePreferece;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.MessageAdapter;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.entity.Message;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.CustomListView;
import com.cloudcc.mobile.weight.CustomListView.OnRefreshListener;
import com.lidroid.xutils.exception.DbException;
import com.litesuits.android.log.Log;

public class MessageActivity extends BaseActivity implements OnClickListener {
	private CustomListView listview;
	private List<Message> list = new ArrayList<Message>();
	private MessageAdapter adapter;
	private Context context;
	private ImageView fanhui;
	private MessageDB db;
	private MessageReceiver receiver;
	private ImageView fanhuibtn;
	private TextView empty;
	private float dx;
	private float ux;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		try {
			context = this;
			setupView();
			addListener();
		} catch (Exception e) {
			Tools.handle(e);
		}
	}

	@Override
	public int getLayoutId() {
		return R.layout.messagelist;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// 当按下时处理
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			dx = ev.getX();
		} else if (ev.getAction() == MotionEvent.ACTION_UP) {// 松开处理
			ux = ev.getX();
			if ((int) (ux - dx) > DensityUtils.getScreenWidth(mContext) / 2
					&& ux > dx) {
				finish();
				// 设置切换动画，从右边进入，左边退出
				overridePendingTransition(R.anim.in_from_left,
						R.anim.out_to_right);
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	protected void onDestroy() {
		try {
			unregisterReceiver(receiver);
		} catch (Exception e) {
			Tools.handle(e);
		}
		super.onDestroy();
	}

	/**
	 * 做监听
	 */
	private void addListener() {
		// 下拉刷新
		listview.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				handler.sendEmptyMessageDelayed(1, 2000);
			}
		});
		// 长按
		listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				// menu.setHeaderTitle("消息操作");
				menu.add(1, 100, 1, "删除消息");
				menu.add(1, 101, 2, "清空消息");
			}
		});

	}

	// 上下文菜单
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		try {
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
					.getMenuInfo();
			Message message = adapter.getItem(info.position - 1);
			switch (item.getItemId()) {
			case 100:
				db.deleteById(Message.class, message.getId());
				list = db.findAllMessage(Message.class);
				Log.d("jdhsj",message.getId() );
				Collections.reverse(list);// 倒序排列
				isEmpty();
				adapter.changeData(list);
				NotificationUtils.clearNotification(context, 2000);
				Intent messageNum = new Intent(AppContext.MESSAGE_SYSTEM_NUM);
				context.sendBroadcast(messageNum);
				break;
			case 101:
				db.deleteAll(Message.class);
				list = db.findAllMessage(Message.class);
				Collections.reverse(list);// 倒序排列
				isEmpty();
				adapter.changeData(list);
				NotificationUtils.clearNotification(context, 2000);
				Intent messageNum2 = new Intent(AppContext.MESSAGE_SYSTEM_NUM);
				context.sendBroadcast(messageNum2);
				break;
			default:
				break;
			}
		} catch (DbException e) {
			Tools.handle(e);
		}
		return super.onContextItemSelected(item);
	}

	private void isEmpty() {
		if (list.size() > 0) {
			empty.setVisibility(View.GONE);
			listview.setVisibility(View.VISIBLE);
			adapter.changeData(list);
		} else {
			empty.setVisibility(View.VISIBLE);
			listview.setVisibility(View.GONE);
		}
	}
@Override
protected void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
	try {
		list = db.findAllMessage(Message.class);
		Collections.reverse(list);// 倒序排列
		isEmpty();
		adapter.changeData(list);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
}
	/**
	 * 获取控件的
	 * 
	 * @param view
	 * @throws DbException
	 */
	private void setupView() throws DbException {
		listview = (CustomListView) findViewById(R.id.messagelist);
		empty = (TextView) findViewById(R.id.empty);
		fanhuibtn = (ImageView) findViewById(R.id.fanhui_message);
		fanhuibtn.setOnClickListener(this);
		listview.setDivider(null);
		// getLastUser();
		adapter = new MessageAdapter(context, list);
		listview.setAdapter(adapter);
		db = new MessageDB(context, UserManager.getManager().getUser().userId
				+ "message");
		if (db.isExit()) {
			list = db.findAllMessage(Message.class);// 查询所有的用户
			Collections.reverse(list);// 倒序排列
			adapter.changeData(list);
			empty.setVisibility(View.GONE);
			listview.setVisibility(View.VISIBLE);
		} else {
			empty.setVisibility(View.VISIBLE);
			listview.setVisibility(View.GONE);
		}

		// 注册广播
		receiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.MESSAGE_SYSTEM);
		registerReceiver(receiver, filter);

		if (db.isExit()) {
			db.clearMessageNum();
			Intent messageNum = new Intent(AppContext.MESSAGE_SYSTEM_NUM);
			context.sendBroadcast(messageNum);
		}
	}

	/**
	 * 获取最后的登陆人
	 */
	private void getLastUser() {
		SharePreferece share = new SharePreferece(context);
		Map<String, ?> user = share.getShare("lastUser");
		UserManager.getManager().getUser().userId = (String) user
				.get("lastUser");
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			try {
				switch (msg.what) {
				case 1:
					list = db.findAllMessage(Message.class);// 查询所有的用户
					Collections.reverse(list);// 倒序排列
					adapter.changeData(list);
					isEmpty();
					listview.onRefreshComplete();
					break;

				default:
					break;
				}
			} catch (DbException e) {
				Tools.handle(e);
			}
			super.handleMessage(msg);
		}
	};

	class MessageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			getLastUser();
			if (action.equals(AppContext.MESSAGE_SYSTEM)) {
				db = new MessageDB(context,
						UserManager.getManager().getUser().userId + "message");
				try {
					list = db.findAllMessage(Message.class);
					Log.d("listslentgh", "changdu:::"+list.size());
					Collections.reverse(list);// 倒序排列
					Intent intents = new Intent(MessageActivity.this, MessageActivity.class);
					startActivity(intents);
					isEmpty();
				} catch (Exception e) {
					Log.d("listslentgh", "changdu:::"+e.getMessage());
					e.printStackTrace();
				}// 查询所有的用户
				
				
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.fanhui_message:
			MessageActivity.this.finish();
			break;
		default:
			break;
		}

	}
}
